package com.tz.farmer.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartPark.msframe.result.ResultEx;
import com.tz.farmer.enums.ErrorCodeEnum;
import com.tz.farmer.mapper.FarmerRoleInfoMapper;
import com.tz.farmer.mapper.FarmerUserInfoMapper;
import com.tz.farmer.model.FarmerRoleInfo;
import com.tz.farmer.model.FarmerUserInfo;
import com.tz.farmer.service.FarmerUserInfoService;
import com.tz.farmer.so.FarmerUserInfoSo;

import com.tz.farmer.util.BeanConvertUtils;
import com.tz.farmer.util.ResultExM;
import com.tz.farmer.vo.FarmerUserInfoVo;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SmartAdminUserInfoServiceImpl
 * @Description TODO
 * @Creator kaikai
 * @Date 2021/5/11 17:14
 */
@Service
public class FarmerUserInfoServiceImpl extends ServiceImpl<FarmerUserInfoMapper, FarmerUserInfo> implements FarmerUserInfoService {

    @Resource
    FarmerUserInfoMapper farmerUserInfoMapper;
    @Resource
    FarmerRoleInfoMapper farmerRoleInfoMapper;

    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public ResultEx getAdminUserListByConditions(FarmerUserInfoSo so) {

        Page<FarmerUserInfo> page = (Page<FarmerUserInfo>)farmerUserInfoMapper.selectPage(
                new Page(so.getCurrentPage(), so.getPageSize())
                , new QueryWrapper<FarmerUserInfo>()
                        .like(StringUtils.isNotEmpty(so.getName()), "name", so.getName())
                        .or()
                        .like(StringUtils.isNotEmpty(so.getUserPhone()), "user_phone", so.getUserPhone())
                        .or()
                        .like(StringUtils.isNotEmpty(so.getUserAccount()), "user_account", so.getUserAccount()).orderByDesc("create_time")
        );

        Map<String, Object> map = new Hashtable<>();
        map.put("total", page.getTotal());
        List<FarmerUserInfo> list = page.getRecords();
        for (FarmerUserInfo farmerUserInfo : list ) {
            FarmerRoleInfo roleInfo = farmerRoleInfoMapper.selectById(farmerUserInfo.getRoleId());
            farmerUserInfo.setRoleName(roleInfo.getRoleName());
        }
        map.put("data", list);
        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED, map);
    }

    @Transactional
    @Override
    public ResultEx updateAdminUserInfo(FarmerUserInfoSo so) {
        if (ObjectUtils.isEmpty(so) || StringUtils.isEmpty(so.getFlag())) {
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
        if (so.getFlag().equals("1")) {
            if("".equals(so.getName()) || "".equals(so.getUserAccount()) || "".equals(so.getPassword()) || "".equals(so.getUserPhone())){
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
            }
            int have = this.count(new QueryWrapper<FarmerUserInfo>()
                    .eq(StringUtils.isNotEmpty(so.getName()), "user_account", so.getUserAccount()));
            if (have > 0) {
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_NO_ACCOUNT_ERROR);
            }
            FarmerUserInfo farmerUserInfo = BeanConvertUtils.copyProperties(so, FarmerUserInfo.class);
            try {
                /**
                 * 给密码加密存储
                 */
                farmerUserInfo.setPassword(DigestUtils.md5DigestAsHex(farmerUserInfo.getPassword().getBytes()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            farmerUserInfo.setCreateTime(LocalDateTime.now());
            boolean insert = this.save(farmerUserInfo);
            if (insert) {
                return ResultEx.builder().makeSuccessResult();
            }

            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_INSERT_FAIL_ERROR);
        } else if (so.getFlag().equals("2")) {
            if (so.getId() == null || so.getId() <= 0) {
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
            }

            FarmerUserInfo farmerUserInfo = BeanConvertUtils.copyProperties(so, FarmerUserInfo.class);
            if (StringUtils.isNotEmpty(so.getPassword())) {
                try {
                    /**
                     * 给密码加密存储
                     */
                    farmerUserInfo.setPassword(DigestUtils.md5DigestAsHex(farmerUserInfo.getPassword().getBytes()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            farmerUserInfo.setCreateTime(LocalDateTime.now());
            boolean update = this.updateById(farmerUserInfo);
            if (update) {
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);
            }
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_UPDATE_FAIL_ERROR);
        } else {
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
    }

    @Transactional
    @Override
    public ResultEx editPassword(FarmerUserInfoSo so) {
        String password=farmerUserInfoMapper.selectPasswordByUserAccount(so.getUserAccount());
        if (!password.equals(DigestUtils.md5DigestAsHex(so.getOldPassword().getBytes()))) {
            return ResultEx.builder().makeFailedResult("旧密码不正确");
        }
        farmerUserInfoMapper.editPassword(DigestUtils.md5DigestAsHex(so.getNewPassword().getBytes()),so.getUserAccount());
        return ResultEx.builder().makeSuccessResult("修改成功");
    }


    @Override
    public List<FarmerUserInfoVo> getUserDownLoadList(FarmerUserInfoSo so) {
        List<FarmerUserInfoVo> listVo = new ArrayList<>();
        List<FarmerUserInfo> list =  farmerUserInfoMapper.selectList(
              new QueryWrapper<FarmerUserInfo>()
                        .like(StringUtils.isNotEmpty(so.getName()), "name", so.getName())
                        .like(StringUtils.isNotEmpty(so.getUserPhone()), "user_phone", so.getUserPhone())
                        .like(StringUtils.isNotEmpty(so.getUserAccount()), "user_account", so.getUserAccount())
        );
       if(CollectionUtils.isNotEmpty(list) || list.size() > 0){
           for ( int i = 0 ; i<list.size() ; i++) {
               FarmerUserInfoVo farmerUserInfoVo = BeanConvertUtils.copyProperties(list.get(i), FarmerUserInfoVo.class);
               FarmerRoleInfo roleInfo = farmerRoleInfoMapper.selectById(list.get(i).getRoleId());
               farmerUserInfoVo.setRoleName(roleInfo.getRoleName());
               LocalDateTime createTime = list.get(i).getCreateTime();
               DateTimeFormatter sf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
               farmerUserInfoVo.setCreateTime(sf.format(createTime));
               listVo.add(farmerUserInfoVo);
           }
       }
       if(CollectionUtils.isEmpty(listVo) || listVo.size() < 0){
           return new ArrayList<>();
       }
        return  listVo;
    }

    @Override
    public ResultEx deleteUser(FarmerUserInfoSo so) {
        if(so.getId() == null || "".equals(so.getId())){
            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
        int flag = farmerUserInfoMapper.delete(new QueryWrapper<FarmerUserInfo>().eq("id", so.getId()));
        if(flag > 0){
            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);
        }
        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_FAIL);
    }

    @Override
    public ResultEx businessSelect(String userAccount ) {
        String roleName = farmerUserInfoMapper.selectRoleNameByAccount(userAccount);
        String businessCode = null;
        String city = null;
        if("源头主体企业".equals(roleName)){
            businessCode = farmerUserInfoMapper.selectUniscIdByAccount(userAccount);
        }else{
            String  cityName = farmerUserInfoMapper.selectAssressByAccount(userAccount);
            if("台州市".equals(cityName)){
                businessCode = null;
                city = null;
            }else {
                city = cityName;
            }
        }
        List<Map<String,Object>> list= farmerUserInfoMapper.businessSelect(businessCode,city);
        return ResultEx.builder().makeSuccessResult(list);
    }
    @Override
    public ResultEx updateUserInfo(String phone,String employeeCode) throws Exception{
        String sql = "update farmer_user_info set employee_code='" + employeeCode + "' where user_phone='" + phone + "'";
        jdbcTemplate.execute(sql);
        return ResultEx.builder().makeSuccessResult("绑定成功");

    }

    @Override
    public List<Map<String,Object>> ifHave(String employeeCode) throws Exception{
        String sql = "select user_account,id from farmer_user_info where  employee_code='" + employeeCode + "' ";
        List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
        return list;

    }

    @Override
    public List<Map<String,Object>> selectUserInfoByPhone(String phone) throws Exception{
        String sql = "select user_account,id from farmer_user_info where  user_phone='" + phone + "' ";
        List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
        return list;

    }

    @Override
    public ResultEx phoneExist(String phone) throws Exception{
        String sql = "select count(1) from farmer_user_info where  user_phone='" + phone + "'";
        int count=jdbcTemplate.queryForObject(sql,Integer.class);
        if(count>0){
            return ResultEx.builder().makeSuccessResult();
        }else{
            return ResultEx.builder().makeFailedResult("该手机号在本系统中未注册！");

        }

    }

}
